package com.carleasoft.mps.security.permission.access;

import com.carleasoft.mps.security.permission.constants.SecurityConsts;
import feign.RequestInterceptor;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 * @author taoyujing
 * @date 2021-09-26 12:48
 * @project services
 */
@Component
public class RibbonConfig {

    /**
     * 解决feign调用丢失token解决方案， 新增拦截器
     *
     * @return
     */
    @Bean
    public RequestInterceptor requestInterceptor() {
        return template -> {
            ServletRequestAttributes attributes = (ServletRequestAttributes)RequestContextHolder.getRequestAttributes();
            if (attributes != null) {
                HttpServletRequest request = attributes.getRequest();
                if (request == null) {
                    return;
                } else {
                    String token = request.getHeader(SecurityConsts.REQUEST_TOKEN_HEADER);
                    template.header(SecurityConsts.REQUEST_TOKEN_HEADER, token);
                }
            }

        };
    }
}
